package cn.edu.ncu.housinghub.controller.message;

import cn.edu.ncu.housinghub.entity.chatsession.ChatMessage;
import cn.edu.ncu.housinghub.service.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import static cn.edu.ncu.housinghub.config.RabbitMQConfig.CHAT_MESSAGE_QUEUE;

@Component
@RequiredArgsConstructor
public class ChatMessageConsumer {

    private final SimpMessagingTemplate messagingTemplate;
    private final ChatService chatService;

    /**
     * 消费聊天消息并推送给接收者
     */
    @RabbitListener(queues = CHAT_MESSAGE_QUEUE)
    public void handleChatMessage(ChatMessage message) {
        try {
            System.out.println("RabbitMQ消费者收到消息: " + message);

            // 推送消息给接收者
            String destination = "/user/" + message.getReceiverId() + "/queue/chat";
            messagingTemplate.convertAndSend(destination, message);
            System.out.println("消息推送给接收者: " + destination);

            // 推送未读消息数量更新
            int unreadCount = chatService.getUnreadCount(message.getSessionId(), message.getReceiverId());
            messagingTemplate.convertAndSend(
                    "/user/" + message.getReceiverId() + "/queue/unread",
                    "{\"sessionId\":" + message.getSessionId() + ", \"count\":" + unreadCount + "}"
            );
            System.out.println("未读消息数量推送完成: " + unreadCount);

        } catch (Exception e) {
            System.err.println("RabbitMQ消息处理失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}